/**
 * Course conflict detection tool: Determine whether newly added courses overlap with existing course times
 * @param {Object} newCourse - New course information (including day, startTime, endTime)
 * @param {Array} existingCourses - List of existing courses
 * @returns {Object} Conflict result (hasConflict: Boolean value, conflictCourse: conflicting course object)
 */
export const checkCourseConflict = (newCourse, existingCourses) => {
  // If there are no comparable courses, return directly without conflict
  if (existingCourses.length === 0) {
    return { hasConflict: false, conflictCourse: null }
  }

  // Convert time to timestamp (for easy comparison)
  const convertTimeToTimestamp = (time) => {
    const [hours, minutes] = time.split(':').map(Number)
    return hours * 60 + minutes // Convert to 'minutes' (e.g. 09:00=540 minutes)
  }

  // Traverse existing courses and check for time overlap in the same week
  for (const course of existingCourses) {
    // 1. First, determine if it is the same day (same week)
    if (course.day !== newCourse.day) {
      continue // No conflicts on different days, skip
    }

    // 2. Convert time to minutes
    const newStart = convertTimeToTimestamp(newCourse.startTime)
    const newEnd = convertTimeToTimestamp(newCourse.endTime)
    const existStart = convertTimeToTimestamp(course.startTime)
    const existEnd = convertTimeToTimestamp(course.endTime)

    // 3. Time overlap logic: The "start time of the new course is less than 
    // the end time of the existing course" and the "end time of the new course 
    // is greater than the start time of the existing course"
    const isConflict = newStart < existEnd && newEnd > existStart
    if (isConflict) {
      return { hasConflict: true, conflictCourse: course }
    }
  }

  // No conflict
  return { hasConflict: false, conflictCourse: null }
}